
// 顶点着色器
const vs_s = `
  attribute vec4 a_Position;
  attribute float a_PointSize;
  void main() {
    gl_Position = a_Position;
    gl_PointSize = a_PointSize;
  }
`;
// 片元着色器
const fs_s = `
  void main() {
    gl_FragColor = vec4(1, 0, 0, 1);
  }
`;

function main() {
  const canvas = document.getElementById('webgl');
  if (!canvas) {
    alert('Field to get canvas by id');
    return false;
  }
  const gl = canvas.getContext('webgl');
  if (!gl) {
    alert('Field to get webgl context.');
    return false;
  }
  if (!initShaders(gl, vs_s, fs_s)) {
    alert('Field to init shaders.');
    return false;
  }
  const pointCount = initVertexBuffers(gl);
  if (pointCount < 0) {
    alert('Field to init vertex buffers.');
    return false;
  }

  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.POINTS, 0, pointCount);

  return true;
}

function initVertexBuffers(gl) {
  // 定义顶点坐标数据
  const vertices = new Float32Array([
    0.0, +0.5,
    0.0, +0.0,
    0.0, -0.5,
  ]);
  // 创建缓存区
  const vertexBuffer = gl.createBuffer();
  if (!vertexBuffer) {
    alert('Field to create vertex buffer.');
    return -1;
  }
  // 绑定缓存区到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 向缓存区写入数据
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  // 获取 attribute 的存储变量
  const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if (a_Position < 0) {
    alert('Field to get vertex attribute.');
    return -1;
  }
  // 将缓存区的顶点数据分配给 attribute
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  // 激活缓存区
  gl.enableVertexAttribArray(a_Position);

  // 定义顶点大小数据
  const sizes = new Float32Array([
    10.0,
    20.0,
    30.0,
  ]);
  // 创建缓存区
  const sizeBuffer = gl.createBuffer();
  if (!sizeBuffer) {
    alert('Field to create size buffer');
    return -1;
  }
  // 绑定缓存区到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, sizeBuffer);
  // 向缓存区中写入顶点大小数据
  gl.bufferData(gl.ARRAY_BUFFER, sizes, gl.STATIC_DRAW);
  // 获取 attribute 的 顶点大小 存储参数
  const a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
  if (a_PointSize < 0) {
    alert('Field to get point size attribute.');
    return -1;
  }
  // 将 顶点大小缓存区 的数据 分配给 顶点大小 attribute
  gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, 0, 0);
  // 激活缓存区
  gl.enableVertexAttribArray(a_PointSize);

  return Math.ceil(vertices.length / 2);
}